using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using CollabApp.Domain.Services.Rankings;

namespace CollabApp.API.HostedServices;

public class RankingSyncHostedService : BackgroundService
{
	private readonly ILogger<RankingSyncHostedService> _logger;
	private readonly IServiceScopeFactory _scopeFactory;

	public RankingSyncHostedService(ILogger<RankingSyncHostedService> logger, IServiceScopeFactory scopeFactory)
	{
		_logger = logger;
		_scopeFactory = scopeFactory;
	}

	protected override async Task ExecuteAsync(CancellationToken stoppingToken)
	{
		_logger.LogInformation("RankingSyncHostedService started");
		while (!stoppingToken.IsCancellationRequested)
		{
			try
			{
				var now = DateTime.Now;
				var nextMidnight = now.Date.AddDays(1); // 本地时间次日00:00
				var delay = nextMidnight - now;
				_logger.LogInformation("Ranking sync scheduled in {Delay} (until {Next})", delay, nextMidnight);
				await Task.Delay(delay, stoppingToken);

				// 到点执行同步
				_logger.LogInformation("Running daily ranking sync at {Time}", DateTime.Now);
				using (var scope = _scopeFactory.CreateScope())
				{
					var service = scope.ServiceProvider.GetRequiredService<IRankingService>();
					await service.SyncOverallRankingToPgsqlAsync();
				}
				_logger.LogInformation("Daily ranking sync completed at {Time}", DateTime.Now);
			}
			catch (TaskCanceledException)
			{
				// 应用停止
				break;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Error occurred during daily ranking sync");
				// 避免热循环：如果异常，等待1分钟后再进入下一轮
				try { await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken); } catch { }
			}
		}
		_logger.LogInformation("RankingSyncHostedService stopped");
	}
}


